#!/usr/bin/env python
# -*- coding:UTF-8 -*-
# Project: devops
#  Author: an00
#  Create: 2018/6/24 11:25


from rest_framework import serializers
from cabinet.models import Cabinet
# from idcs.serializers import IdcSerializer
from idcs.models import Idc


class CabinetSerializer(serializers.Serializer):
    """
    机柜序列化，Serializer方式可以用
    PrimaryKeyRelatedField取外键关联的主键，传入queryset，若字段对应单个则many=False，一对多可以用True
    """
    id = serializers.IntegerField(read_only=True)
    idc = serializers.PrimaryKeyRelatedField(queryset=Idc.objects.all(), many=False)
    # idc = IdcSerializer()  # 会取出idc所有数据
    # idc = serializers.SerializerMethodField()
    name = serializers.CharField(max_length=128, label='机柜名称', help_text='机柜详细名称')

    # def get_idc(self, obj):
    #     return {'id': obj.id, 'idc_name': obj.name}

    def to_representation(self, instance):
        """
        将对象实例转换成原始数据类型，解析后返回给客户端
        定义返回内容，可以从instance增加或删除信息
        :param instance:
        :return:
        """
        idc_obj = instance.idc
        # result = super().to_representation(instance)
        result = super(CabinetSerializer, self).to_representation(instance)
        result['idc'] = {'id': idc_obj.id,
                         'idc_name': idc_obj.name}
        return result

    def to_internal_value(self, data):
        """
        反序列化第一步，数据拿到经过的第一个方法，将客户端传来的json数据解析给Model
        :param data:
        :return:
        """
        print(data)
        return super(CabinetSerializer, self).to_internal_value(data)

    def create(self, validated_data):
        return Cabinet.objects.create(**validated_data)

    def update(self, instance, validated_data):
        instance.idc = validated_data['idc']
        instance.save()
        return instance
